/*********************************************************
 * File Name   : Singleton.c
 * Author      : Elvis Wang
 * Mail        : huan.wang@ingenic.com
 * Created Time: 2019-06-06 15:42
 ********************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>

#include "dp.h"

#define SINGLETON_VERSION "Singleton v1.0.0"

typedef struct _GlobalSetting {
	char dp_version[128];
	char sg_version[128];
	int module_refcnt;
} GlobalSetting;

pthread_mutex_t gs_mutex;
static GlobalSetting *gs = NULL;

GlobalSetting *get_global_setting(void)
{
	pthread_mutex_lock(&gs_mutex);
	if (!gs) {
		gs = (GlobalSetting *)malloc(sizeof(GlobalSetting));
		if (!gs) {
			printf("%s: malloc Globalsetting error!\n", __func__);
			return NULL;
		}
		memcpy(gs->dp_version, DP_VERSION, strlen(DP_VERSION));
		memcpy(gs->sg_version, SINGLETON_VERSION, strlen(SINGLETON_VERSION));
	}
	gs->module_refcnt++;
	pthread_mutex_unlock(&gs_mutex);

	return gs;
}

void release_global_setting(void)
{
	pthread_mutex_lock(&gs_mutex);
	if (gs)
		free(gs);
	pthread_mutex_unlock(&gs_mutex);
}

int main()
{
	pthread_mutex_init(&gs_mutex, NULL);
	GlobalSetting *gs0 = get_global_setting();
	if (!gs0) {
		printf("get global setting error!\n");
		return -1;
	}
	printf("gs0[%p] dp_version:[%s], sg_version:[%s], module_refcnt:[%d]\n", gs0, gs0->dp_version, gs0->sg_version, gs0->module_refcnt);

	GlobalSetting *gs1 = get_global_setting();
	printf("gs1[%p] dp_version:[%s], sg_version:[%s], module_refcnt:[%d]\n", gs1, gs1->dp_version, gs1->sg_version, gs1->module_refcnt);

	GlobalSetting *gs2 = get_global_setting();
	printf("gs2[%p] dp_version:[%s], sg_version:[%s], module_refcnt:[%d]\n", gs2, gs2->dp_version, gs2->sg_version, gs2->module_refcnt);

	release_global_setting();

	return 0;
}
